package core.db;
import java.beans.PropertyVetoException;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
import java.util.Map;
import java.util.Set;

import javax.naming.NameAlreadyBoundException;
import javax.naming.NameNotFoundException;

import com.mchange.v2.c3p0.ComboPooledDataSource;

import core.util.CommUtils;
import core.util.CoreDataUtil;
/**
 * 数据库链接统计类
 * @author qiwx
 *
 */
public class DBConnectionUtil {
  private static org.apache.log4j.Logger log = core.util.Logger.getLogger(DBConnectionUtil.class);
  /**
   * 初始化 数据源,每个数据源建立连接池
   * @throws NameNotFoundException
   * @throws NameAlreadyBoundException
   * @throws SQLException
   * @throws PropertyVetoException 
   */
  public static void init() throws NameNotFoundException, NameAlreadyBoundException, SQLException, PropertyVetoException{
     Map<String, Object> map = CoreDataUtil.dataSourceMap;
     if ( CommUtils.isNotNullMap(map) ) {
        Set<String> keys = map.keySet();
        for ( String key : keys ) {
          DBConnectionDataSource ds = (DBConnectionDataSource)map.get(key);
          ComboPooledDataSource cpds=new ComboPooledDataSource(); 
          cpds.setDataSourceName( key );
          cpds.setDriverClass( ds.getDriver() );
          cpds.setJdbcUrl( ds.getUrl() );
          cpds.setUser(ds.getUser());
          cpds.setPassword(ds.getPassword());
          cpds.setInitialPoolSize(ds.getInitCnt());
          cpds.setMinPoolSize( ds.getMinConnection() );  
          cpds.setMaxPoolSize( ds.getMaxConnection() ); 
          cpds.setIdleConnectionTestPeriod((int)ds.getIdleConnectonTestPeriodTime());
          cpds.setMaxIdleTime( (int)ds.getTimeout() );
          cpds.setAutoCommitOnClose(false);
          cpds.setCheckoutTimeout( (int)ds.getWaitTime());
          cpds.setMaxStatements( ds.getMaxstatementsInt() );
          log.info("load the datasource....>"+ key);
          CoreDataUtil.dataMap.put(key, cpds);
        }
     }
  }
  
  /** hegp
   * 返回数据源dataSource
   * @param dataSource
   * @return
   * @throws Exception
   */
  public static Connection getDBConnection( String dataSource ) throws Exception {
    
	  ComboPooledDataSource cpds = (ComboPooledDataSource)CoreDataUtil.dataMap.get( dataSource );
	  Connection con = cpds.getConnection();
	  con.setAutoCommit(false);
	/*  String url = "jdbc:mysql://117.27.234.245:8012/voip_plat_version2?useUnicode=true&amp;characterEncoding=UTF-8";
	  String name = "root";
	  String passwd = "123456";
	  Connection con = DBConnectionUtil.getDBConnection(url, name, passwd);*/
	  
	  return con;
	  
  }
    
  
	/**
	 * 修改点：之前是整体捕捉异常，关闭过程中出现了异常可能会造成部分资源未释放
	 * 
	 * @param rs
	 * @param stmt
	 * @param con
	 */
	public static void close(ResultSet rs, Statement stmt, Connection con) {
		if (rs != null) {
			try {
				rs.close();
			} catch (SQLException e) {
				log.error("关闭数据库结果集失败", e);
			}
		}
		if (stmt != null) {
			try {
				stmt.close();
			} catch (SQLException e) {
				log.error("关闭数据库语句失败", e);  
			}
		}

		try {
			if (con != null && !con.isClosed()) {
				if (!con.getAutoCommit()) {
					con.commit();
					con.setAutoCommit(true);
				}
				con.close();
			}
		} catch (SQLException e) {    
			log.error("关闭数据库连接失败", e);
		}

	}
  public static void rollBack( Connection conn ) {
    log.info("....回滚数据库....");
    try { 
      if(conn != null ){
        if (!conn.getAutoCommit()) {
          conn.rollback();
        }
      }
    } catch (SQLException e) {
      log.error(" SQLException ==>", e);
    }
  }
  
  /**
   * 获得mysql链接
   * @param url
   * @param userName
   * @param pwd
   * @return
   */
  public static Connection getDBConnection( DBConnectionDataSource ds ){
    Connection conn = null;
    try {
      Class.forName(ds.getDriver()).newInstance();
      conn = DriverManager.getConnection(ds.getUrl(), ds.getUser(), ds.getPassword());
    } catch (Exception e) {
      e.printStackTrace();
    }
    return conn;
  }   
  /**
   * 获得mysql链接
   * @param url
   * @param userName
   * @param pwd
   * @return
   */
  public static Connection getDBConnection(String url, String user, String passwrod){
    Connection conn = null;
    try {
      Class.forName("com.mysql.jdbc.Driver").newInstance();
      conn = DriverManager.getConnection(url, user, passwrod);
    } catch (Exception e) {
      e.printStackTrace();
    }
    return conn;
  }   
}
